using System;
using System.IO;
using System.Net;
using System.Web;
using System.Web.UI.HtmlControls;
using log4net;
namespace CommonTagTime
{
    public class clsFile
    {
        public static void WriteLog(string ClassName, string FunctionName, string Error)
        {
            //for logging to file
            log4net.ILog logger = log4net.LogManager.GetLogger("File");            
            logger.Info(FunctionName + "_" + Error);
            //HttpContext.Current.Response.Write(Error);
        }

        public static void WriteLog(string FunctionName, string Error)
        {
            HttpContext.Current.Response.Write(Error);
        }

        //public static void WriteLog(string Error)
        //{
        //    HttpContext.Current.Response.Write(Error);
        //}

        public bool Download(string path, string file)
        {
            try
            {
                string strURL = HttpContext.Current.Request.Path.ToString() + "//" + path + "//" + file;

                WebClient req = new WebClient();
                CredentialCache mycache = new CredentialCache();
                mycache.Add(new Uri(strURL), "Basic", new NetworkCredential());
                req.Credentials = mycache;
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.ClearContent();
                response.ClearHeaders();
                response.Buffer = true;
                response.AddHeader("Content-Disposition", "attachment;filename=\"" + file + "\"");
                byte[] data = req.DownloadData(strURL);
                response.BinaryWrite(data);
                response.End();

                return true;
            }
            catch (Exception ex)
            {
                if (ex.Message == "The remote server returned an error: (404) Not Found.")
                {
                    throw new Exception("File not found");
                }
                if (ex.Message == "The remote server returned an error: (401) Unauthorized.")
                {
                    throw new Exception("Unauthorized access");
                }

                return false;
            }
        }

        public string[] GetFiles(string strPath)
        {
            return Directory.GetFiles(strPath);
        }

        public string GetModifyDate(string strPath)
        {
            return Directory.GetCreationTime(strPath).ToString();
        }

        public bool IsExist(string strFilePathName)
        {
            return File.Exists(strFilePathName);
        }

        public string Read(string strFilePathName)
        {
            string str = "";
            StreamReader objStream = File.OpenText(strFilePathName);
            objStream.BaseStream.Seek((long) 0, SeekOrigin.Begin);
            while (objStream.Peek() > -1)
            {
                str = str + objStream.ReadLine() + '\r';
            }
            objStream.Close();
            objStream = null;
            return str;
        }

        public string ReadFirstLine(string strFilePathName)
        {
            string str = "";
            StreamReader objStream = File.OpenText(strFilePathName);
            objStream.BaseStream.Seek((long) 0, SeekOrigin.Begin);
            if (objStream.Peek() > -1)
            {
                str = objStream.ReadLine();
            }
            objStream.Close();
            objStream = null;
            return str;
        }

        public void Remove(string strFilePathName)
        {
            if (File.Exists(strFilePathName))
            {
                File.Delete(strFilePathName);
            }
        }

        public void Move(string SourceFileName, string DestinationFileName)
        {
            if (File.Exists(SourceFileName))
            {    
                File.Move(SourceFileName, DestinationFileName);
            }
        }

        public void Replace(string SourceFileName, string DestinationFileName)
        {
            if (File.Exists(SourceFileName))
            {
                if (File.Exists(DestinationFileName))
                {
                    File.Delete(DestinationFileName);
                }

                File.Move(SourceFileName, DestinationFileName);
            }
        }

        public void Copy(string SourceFileName, string DestinationFileName)
        {
            if (File.Exists(SourceFileName))
            {
                File.Copy(SourceFileName, DestinationFileName, true);
            }
        }

        public void Rename(string strFilePathName, string strToFile)
        {
            if (File.Exists(strFilePathName))
            {
                File.Move(strFilePathName, strToFile);
            }
        }

        public void Upload(HtmlInputFile FileURL, string strPathFileName)
        {
            try
            {
                if (FileURL.PostedFile.FileName != "")
                {
                    FileURL.PostedFile.SaveAs(strPathFileName);
                }
            }
            catch (Exception ex)
            {
                WriteLog("clsFile", "Upload",  ex.ToString());
            }
        }

        public bool Write(string path, string text)
        {
            bool flag = false;
            FileStream file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(file);
            try
            {
                try
                {
                    sw.Write(text);
                    sw.Flush();
                    flag = true;
                    sw.Dispose();
                }
                catch (Exception ex)
                {
                    WriteLog("clsFile", "Write", ex.ToString());
                }
            }
            finally
            {
                sw.Close();
                file.Close();
                sw = null;
            }
            return flag;
        }

        public string GetFileContents(string path)
        {
            try
            {
                string content;
                path = HttpContext.Current.Server.MapPath(path);

                if (!File.Exists(path))
                    return "";

                StreamReader sr = new StreamReader(path);
                content = sr.ReadToEnd();
                sr.Close();

                return content;
            }
            catch (Exception ex)
            {
                // Ignore any errors
            }

            return "";
        }

        public static bool DeleteFile(string path)
        {
            try
            {
                File.Delete(path);
                return true;
            }
            catch
            {
            }
            return false;
        }
   
    }
}